package utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 把重复代码单独拎出来，减小代码量
 * User: 王圆豪
 * Date: 2025-04-13
 * Time: 17:07
 */
public class DBUtil {
    public static DataSource dataSource = null;

    public static final String URL = "jdbc:mysql://127.0.0.1:3306/java113?cha" +
            "racterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false";

    public static final String USER = "root";

    public static final String PASSWORD = "123456";

    static {
        //定义Mysql数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //设置数据库连接串
        mysqlDataSource.setURL(URL);
        //用户名
        mysqlDataSource.setUser(USER);
        //密码
        mysqlDataSource.setPassword(PASSWORD);
        //定义JDBC数据源对象
        dataSource = mysqlDataSource;
    }

    //通过数据源获取数据库连接
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //构造方法私有化，防止new这个对象
    private DBUtil(){}

    //关闭连接，释放资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
